package cn.sstir.hackathon.core.http;

import cn.sgst.tool.common.exception.ServiceException;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @title: ClientService
 * @description: TODO
 * @author: fli
 * @email: fli@sstir.cn
 * @date: 2019/7/17 13:38
 */
@Component
public class ClientService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private RequestConfig config;


    /**
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则抛出异常状态码
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url) throws Exception {
        // 声明 http get 请求
        URL URL = new URL(url);
        URI uri = new URI("http",URL.getUserInfo(),URL.getHost(),URL.getPort(),URL.getPath(),URL.getQuery(),null);
        HttpGet httpGet = new HttpGet(uri);
        // 装载配置信息
        httpGet.setConfig(config);

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);
        return getContent(response);
    }

    public String doGet(String url, Map<String, String> paramMap) throws Exception {
        URIBuilder builder = new URIBuilder(url);
        for (String s : paramMap.keySet()) {
            builder.addParameter(s, paramMap.get(s));
        }
        return doGet(builder.build().toString());
    }


    public String doPost(String url, Map<String, Object> map) throws Exception {
        HttpPost httpPost = new HttpPost(new URI(url));
        httpPost.setConfig(config);
        if (map != null) {
            // 声明存放参数的List集合
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // 遍历map，设置参数到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }

            // 创建form表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");
            // 把表单对象设置到httpPost中
            httpPost.setEntity(formEntity);
        }

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpPost);
        return getContent(response);
    }


    private String getContent(CloseableHttpResponse response) throws Exception {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            // 返回响应体的内容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        } else {
            logger.error("错误状态码:{}",statusCode);
            throw new ServiceException(statusCode,"httpclient调取接口失败");
        }
    }

}
